package lucene_db;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class IndexDB {
	public static Connection conn = DB.getConnection();
	static String indexPath = "index";

	public static ResultSet getResult(String sql) {
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			return rs;
		} catch (SQLException e) {
			System.out.println(e);
		}
		return null;
	}

	public static void IndexDB() throws IOException {
		// 创建索引
		
		// Directory dir=new RAMDirectory();
		Directory dir = FSDirectory.open(new File(indexPath));
		Analyzer analyzer = new IKAnalyzer();
		//Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_45);

		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_45,
				analyzer);
		IndexWriter indexWriter = new IndexWriter(dir, config);
		String sql = "select top 10 * from test";
		ResultSet rs = getResult(sql);
		try {
			while (rs.next()) {
				Document doc = new Document();
				String title = rs.getString("title");
				String content = rs.getString("content");
				//System.out.print(content);
				Field f1 = new Field("title", title, TextField.TYPE_STORED);
				Field f2 = new Field("content", content, TextField.TYPE_STORED);
				doc.add(f1);
				doc.add(f2);
				indexWriter.addDocument(doc);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		indexWriter.close();
		DB.closeConnection(conn);
	}

}
